<template>
  <div id='veriFace'>
    <div class='main-header'>
      人脸识别系统-登录
    </div>
    <dv-border-box-7 class='main-container'>
      <dv-border-box-12 class='left-container'>
        人脸识别
        <canvas style='display:none;' id='canvasCamera' :width='videoWidth' :height='videoHeight'></canvas>
        <video id='videoCamera' width='100%' height='100%' autoplay></video>
      </dv-border-box-12>
      <dv-border-box-12 class='right-container'>
        效果预览
        <dv-border-box-12>
          <img :src='imgSrc' width='100%' height='100%' alt class='tx_img' />
        </dv-border-box-12>
        登录注册
        <dv-border-box12>
          <div>
            <a-tabs default-active-key='1' @change='onChange'>
              <a-tab-pane key='1' tab='登录'>
                <a-row style='margin-top:20px;color: whitesmoke' :gutter='10'>
                  <a-col :span='8'>
                    <a-button round @click='searchImage()'>登录</a-button>
                    <br>
                    <br>
                    <a-button round @click='re()'>重新登录</a-button>
                    <br>
                    <br>
                    <a-button round @click='loginByPassword'>密码登录</a-button>
                    <!--                    <br>
                                        <br>
                                        <a-button round @click="faceRegister">人脸注册</a-button>-->
                  </a-col>
                </a-row>
              </a-tab-pane>
              <a-tab-pane key='2' tab='退出'>
                <a-row style='margin-top:20px;color: whitesmoke' :gutter='10'>
                  <a-col :span='8'>
                    <a-button round @click='exit'>退出</a-button>
                  </a-col>
                </a-row>
              </a-tab-pane>


              <!--              <a-tab-pane key="2" tab="注册" force-render>-->
              <!--                <a-row style="margin-top:20px;color: whitesmoke" :gutter="10">-->
              <!--                  <a-col :span="24">-->
              <!--                    工号：-->
              <!--                    <a-select-->
              <!--                      show-search-->
              <!--                      :value="workNo+' '+realname"-->
              <!--                      placeholder="请输入工号"-->
              <!--                      style="width: 200px"-->
              <!--                      :default-active-first-option="false"-->
              <!--                      :show-arrow="false"-->
              <!--                      :filter-option="false"-->
              <!--                      :not-found-content="null"-->
              <!--                      @search="handleSearch"-->
              <!--                      @change="handleChange"-->
              <!--                      @focus="fetchUser('')"-->
              <!--                    >-->
              <!--                      <a-select-option v-for="d in data" :key="JSON.stringify(d)">-->
              <!--                        {{ d.workNo }} {{ d.realname }}-->
              <!--                      </a-select-option>-->
              <!--                    </a-select>-->
              <!--                  </a-col>-->

              <!--                  <a-col style="margin-top: 10px" :span="24">-->
              <!--                    <a-button round @click="register()">注册</a-button>-->
              <!--                  </a-col>-->

              <!--                </a-row>-->
              <!--              </a-tab-pane>-->

            </a-tabs>

          </div>


        </dv-border-box12>
      </dv-border-box-12>
    </dv-border-box-7>
  </div>

</template>
<script>
import { getAction, postAction } from '@api/manage'
import Vue from 'vue'
import user from '../../store/modules/user'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { mapActions } from 'vuex'

export default {
  data() {
    return {
      videoWidth: 1200,
      videoHeight: 600,
      imgSrc: '',
      thisCancas: null,
      thisContext: null,
      thisVideo: null,
      openVideo: false,
      photo: {
        base64Code: '',
        username: ''
      },
      current: 0,
      data: [],
      userInfoId: undefined,
      workNo: '',
      realname: '',
      imgPath: '',
      age: 18,
      sex: '',
      loginFailed: 0,
      loginModel: false,
      timer: null
    }
  },
  mounted() {
    this.getCompetence()
    this.getImage()
  },
  destroyed() {
    clearTimeout(this.timer)
  },
  methods: {
    ...mapActions(['faceLogin']),
    // 调用权限（打开摄像头功能）
    getCompetence() {
      const _this = this
      _this.thisCancas = document.getElementById('canvasCamera')
      _this.thisContext = this.thisCancas.getContext('2d')
      _this.thisVideo = document.getElementById('videoCamera')
      _this.thisVideo.style.display = 'block'
      // 获取媒体属性，旧版本浏览器可能不支持mediaDevices，我们首先设置一个空对象
      if (navigator.mediaDevices === undefined) {
        navigator.mediaDevices = {}
      }

      // 一些浏览器实现了部分mediaDevices，我们不能只分配一个对象
      // 使用getUserMedia，因为它会覆盖现有的属性。
      // 这里，如果缺少getUserMedia属性，就添加它。
      if (navigator.mediaDevices.getUserMedia === undefined) {
        navigator.mediaDevices.getUserMedia = function(constraints) {
          // 首先获取现存的getUserMedia(如果存在)
          const getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.getUserMedia
          // 有些浏览器不支持，会返回错误信息
          // 保持接口一致
          if (!getUserMedia) {//不存在则报错
            return Promise.reject(
              new Error('getUserMedia is not implemented in this browser')
            )
          }
          // 否则，使用Promise将调用包装到旧的navigator.getUserMedia
          return new Promise(function(resolve, reject) {
            getUserMedia.call(navigator, constraints, resolve, reject)
          })
        }
      }
      const constraints = {
        audio: false,
        video: {
          width: this.videoWidth,
          height: this.videoHeight,
          transform: 'scaleX(-1)'
        }
      }
      navigator.mediaDevices
        .getUserMedia(constraints)
        .then(function(stream) {
          // 旧的浏览器可能没有srcObject
          if ('srcObject' in _this.thisVideo) {
            _this.thisVideo.srcObject = stream
          } else {
            // 避免在新的浏览器中使用它，因为它正在被弃用。
            _this.thisVideo.src = window.URL.createObjectURL(stream)
          }
          _this.thisVideo.onloadedmetadata = function() {
            _this.thisVideo.play()
          }
        })
        .catch(err => {
          console.log(err)
        })
    },
    //  绘制图片（拍照功能）
    setImage() {
      const _this = this
      // canvas画图
      _this.thisContext.drawImage(_this.thisVideo, 0, 0, _this.videoWidth, _this.videoHeight)
      // 获取图片base64链接
      _this.imgSrc = this.thisCancas.toDataURL('image/png')//赋值并预览图片
      _this.current = 1
    },

    getImage() {
      this.$message.info('请保持正脸进入屏幕')
      this.timer = setTimeout(() => {
        this.setImage()
      }, 3000)
      this.timer = setTimeout(() => {
        this.searchImage()
      }, 5000)
    },
    // 关闭摄像头
    stopNavigator() {
      this.thisVideo.srcObject.getTracks()[0].stop()
    },
    register() {
      if (this.thisVideo.srcObject == null) {
        this.$message.info('未检测到摄像头或摄像头损坏')
      } else if (this.userInfoId === undefined) {
        this.$notification.open({
          message: '注册失败',
          description: '请录入工号'
        })
      } else {
        let params = {
          age: this.age,
          sex: this.sex,
          groupId: 101,
          userInfoId: this.userInfoId,
          file: this.imgSrc,
          name: this.realname,
          imgPath: 'temp/' + this.workNo + this.realname + '.png'
        }
        postAction('/sys/user/faceAdd', params).then(res => {
          if (res.success) {
            this.$notification.open({
              message: '注册成功',
              description: '用户' + this.realname + '注册成功,信息已录入！',
              onClick: () => {
                console.log('用户注册')
              }
            })
            this.saveImageToLocal()
          } else {
            this.$notification.open({
              message: '注册失败',
              description: res.message + ',请重新拍照'
            })
          }
        })
      }
    },

    searchImage() {
      if (this.thisVideo.srcObject == null) {
        this.$message.info('未检测到摄像头或摄像头损坏')
      } else {
        const _this = this
        let params = { groupId: 101, file: this.imgSrc }
        this.faceLogin(params).then((res) => {
          console.log(res)
          if (res.success) {
            this.$notification.open({
              message: '登陆成功:' + res.result.userName,
              description: '相似度为' + res.result.faceSearchResDto.similarValue + '%，用户获得登录许可！',
              onClick: () => {
                console.log('用户搜索')
              }
            })
            Vue.ls.set('ACCESS_TOKEN', res.result.token)
            //this.mutations.SET_TOKEN()
            user.state.token = res.result.token
            user.state.userRole = res.result.userRole.str1
            localStorage.setItem("role",res.result.userRole.str1)
            /*console.log('1111'+res.result.userRole.str1)*/
            this.$router.push('/toolbox')
          } else {
            this.loginFailed = this.loginFailed + 1
            // const model = this.$error({
            //   title: '错误',
            //   content: '登陆失败！请重试',
            //   okText: '重新登陆',
            //   onOk: () => {
            //     model.destroy()
            //     _this.stopNavigator()
            //     _this.getCompetence()
            //
            //   }
            // })
            this.$message.error('登陆失败' + this.loginFailed + '次')
          }
        }).catch(error => {
          this.loginFailed = this.loginFailed + 1
          // const model = this.$error({
          //   title: '错误',
          //   content: '登陆失败！请重试',
          //   okText: '重新登陆',
          //   onOk: () => {
          //     model.destroy()
          //     _this.stopNavigator()
          //     _this.getCompetence()
          //   }
          // })
          this.$message.error('登陆失败' + this.loginFailed + '次')
        })
      }
    },

    saveImageToLocal() {
      this.photo.base64Code = encodeURI(this.imgSrc).replace(/\+/g, '%2B')
      this.photo.username = this.workNo + this.realname
      postAction('/saveImage', this.photo).then(res => {
        console.log(res)
        this.imgPath = res.result
      })
    },
    // base64转文件
    dataURLtoFile(dataurl, filename) {
      const arr = dataurl.split(',')
      const mime = arr[0].match(/:(.*?);/)[1]
      const bstr = atob(arr[1])
      let n = bstr.length
      const u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new File([u8arr], filename, { type: mime })
    },
    onChange(current) {
      // console.log('onChange:', current);
      this.current = current
    },
    fetchUser(value) {
      /*console.log("value+++:"+value)*/
      let params = { workNo: value }
      /*console.log(params.workNo)*/
      let url = '/sys/user/getSysUserByWorkNo'
      let that = this
      getAction(url, params).then(res => {
        that.data = res.result
      })
    },
    handleSearch(value) {
      /*console.log('value:' + value)*/
      /*fetch(value, data => (this.data = data));*/
      this.fetchUser(value)
    },
    handleChange(value) {
      let user = JSON.parse(value)
      /*console.log('user:' + user)*/
      this.workNo = user.workNo
      this.realname = user.realname
      this.userInfoId = user.id
      console.log(typeof user.birthday)
      this.age = user.birthday
      if (user.birthday != null) {
        let time2 = new Date().getTime() - new Date(user.birthday + ' 00:00:00').getTime()
        let date = new Date(time2)
        this.age = date.getFullYear() - 1970
      }
      this.sex = user.sex
      /*console.log(this.workNo+this.realname+this.userInfoId+this.age+this.sex)*/
      this.fetchUser(value)
    },
    loginByPassword() {
      this.$destroy()
      this.$router.push('/login')
    },
    re() {
      if (this.thisVideo.srcObject == null) {
        this.$message.info('未检测到摄像头或摄像头损坏')
      } else {
        /*this.stopNavigator()
        this.getCompetence()*/
        this.getImage()
      }
    },
    faceRegister() {
      this.$router.push('/faceRegister')
    },
    exit() {
      this.$router.push('/')
    }
  }
}
</script>

<style>
div.ant-tabs-tab {
  color: white;
}
</style>
<style lang='less'>
#veriFace {
  width: 100%;
  height: 100%;
  background-color: #030409;
  color: #fff;
  background-image: url('../../assets/bg.png');;
  background-size: 100% 100%;
  box-shadow: 0 0 3px blue;
  display: flex;
  flex-direction: column;

  .main-header {
    height: 80px;
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
    font-size: 30px;
    margin: 0 auto;
  }

  .main-container {
    height: calc(~"100% - 80px");

    .border-box-content {
      padding: 20px;
      box-sizing: border-box;
      display: flex;
    }
  }

  .left-container {
    width: 70%;
    padding: 10px;
    box-sizing: border-box;

    .border-box-content {
      flex-direction: column;
    }
  }

  .right-container {
    width: 30%;
    padding-left: 5px;
    box-sizing: border-box;

    .border-box-content {
      flex-direction: column;
    }
  }
}
</style>